package cn.ccew.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;

public class FileTool {

	public static void copyFile(File sourceFile, File targetFile) throws IOException {
		// 新建文件输入流并对它进行缓冲
		FileInputStream input = new FileInputStream(sourceFile);
		BufferedInputStream inBuff = new BufferedInputStream(input);
		// 新建文件输出流并对它进行缓冲
		FileOutputStream output = new FileOutputStream(targetFile);
		BufferedOutputStream outBuff = new BufferedOutputStream(output);
		// 缓冲数组
		byte[] b = new byte[1024 * 5];
		int len;
		while ((len = inBuff.read(b)) != -1) {
			outBuff.write(b, 0, len);
		}
		// 刷新此缓冲的输出流
		outBuff.flush();
		// 关闭流
		inBuff.close();
		outBuff.close();
		output.close();
		input.close();
	}

	public static String createDocument(HttpServletRequest request, String fileName) throws IOException {
		String baseUrl = request.getSession().getServletContext().getRealPath("/") + fileName;
		boolean bFile = false;
		String fname = new SimpleDateFormat("yyyyMMdd").format(new Date());
		File dirFile = new File(baseUrl + File.separator + fname);

		bFile = dirFile.exists();
		if (bFile) {
			return fname;
		} else {
			bFile = dirFile.mkdir();
			if (bFile)
				return fname;
			return fname;
		}
	}

	/**
	 * 删除单个文件
	 * 
	 * @param fileName
	 *            被删除文件的文件名
	 * @return 单个文件删除成功返回true,否则返回false
	 */
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		if (file.isFile() && file.exists()) {
			file.delete();
			System.out.println("删除单个文件" + fileName + "成功！");
			return true;
		} else {
			System.out.println("删除单个文件" + fileName + "失败！");
			return false;
		}
	}

	public static String createDocBySet(HttpServletRequest request, String fileName) throws IOException {

		String baseUrl = request.getSession().getServletContext().getRealPath("/") + fileName;
		boolean bFile = false;
		File dirFile = new File(baseUrl);

		bFile = dirFile.exists();
		if (bFile) {
			return fileName;
		} else {
			bFile = dirFile.mkdir();
			if (bFile)
				return fileName;
			return fileName;
		}
	}

	public static String trimExtension(String filename) {
		return filename.substring(filename.lastIndexOf(".") + 1);
	}
}